﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web.UI.WebControls;

namespace PmfWeb.Core.WebControls
{
    ///<summary>
    /// 转换下拉列表值为数据验证类型
    ///</summary>
    
    public class RequiredFieldTypeControlsConverter :StringConverter
    {
        ///<summary>
        /// 构造器
        ///</summary>
        public RequiredFieldTypeControlsConverter()
        {
        }
        


        public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
        {
            return true;
            //return base.GetStandardValuesSupported(context);
        }
        public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            //return base.GetStandardValues(context);
            List<string> lists = new List<string>(15);
            lists.Add("不验证");
            lists.Add("数字验证");
            lists.Add("电子邮箱");
            lists.Add("移动电话");
            lists.Add("住宅电话");
            lists.Add("身份证号码");
            lists.Add("网址验证");
            lists.Add("年月日");
            lists.Add("日期时间");
            lists.Add("货币金额");
            lists.Add("IP地址");
            lists.Add("字母数字下划线");
            return new StandardValuesCollection(lists);
        }

        /// <summary>
        /// 控件验证类型是选择,还是可选择可输入
        /// </summary>
        /// <param name="context"></param>
        /// <returns>true,选择,false,可以输入</returns>
        public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
        {
            return true;  //只能选择,不能输入
            //return base.GetStandardValuesExclusive(context);
        }



    }
    ///<summary>
    /// 扩展TextBox控件
    ///</summary>
    [ToolboxItem("<{0}:TextBox runat=server />")]
    [LicenseProvider(typeof(ExpireLicenseProvider))]
    public class TextBox : System.Web.UI.WebControls.TextBox
    {
        protected RequiredFieldValidator isCanNull = new RequiredFieldValidator();
        protected RegularExpressionValidator reg = new RegularExpressionValidator();
        protected RangeValidator range = new RangeValidator();

        private string _maxValue = string.Empty;
        private string _minValue = string.Empty;
        private string _hintTitle = string.Empty;
        private bool _UpShow = true;
        private string _RequiredFieldType = string.Empty;

        //private License _license;


        ///<summary>
        /// 构造器
        ///</summary>
        public TextBox()
        {
            ///_license = LicenseManager.Validate(typeof (TextBox), this);
        }
        /// <summary>
        /// 
        /// </summary>
        public override void Dispose()
        {
            base.Dispose();
            //if(null!= _license) _license.Dispose();
        }
        ///<summary>
        /// 验证类型
        ///</summary>
        [Bindable(true), Category("Behavior"), DefaultValue(""), TypeConverter(typeof(RequiredFieldTypeControlsConverter)),Description("转换验证类型")]
        public string RequiredFieldType
        {
            get { return _RequiredFieldType; }
            set { _RequiredFieldType = value; }
        }


        /// <summary>
        /// 在控件上面显示提示信息,还是在下边显示提示信息
        /// </summary>
        [Bindable(true), Category("Appearance"), DefaultValue(true), Description("在控件上面显示提示信息,还是在下边显示提示信息")]
        public bool UpShow
        {
            get { return _UpShow; }
            set { _UpShow = value; }
        }

        /// <summary>
        /// 控件提示文字
        /// </summary>
        [Bindable(true),Category("Appearance"),DefaultValue(""),Description("控件提示文字,必须和Hint控件搭配使用才有效.")]
        public string HintTitle
        {
            get { return _hintTitle; }
            set { _hintTitle = value; }
        }

        /// <summary>
        /// 最小值
        /// </summary>
        [Bindable(true), Category("Appearance"),DefaultValue(""),Description("控件可以接受的最小输入值")]
        public string MinValue
        {
            get { return _minValue; }
            set { _minValue = value; }
        }

        ///<summary>
        /// 最大值
        ///</summary>
        [Bindable(true),Category("Appearance"),DefaultValue(""),Description("控件可以接受的最大输入值")]
        public string MaxValue
        {
            get { return _maxValue; }
            set { _maxValue = value; }
        }

        ///<summary>
        /// 最大值
        ///</summary>
        [Bindable(true), Category("Appearance"), TypeConverter(typeof(IsCanEmptyControlConverter)), DefaultValue("可为空"), Description("控件是否可以不输入")]
        public string IsCanEmpty
        {
            get { return (string) (ViewState["Pmf_TextBox_IsCanEmpty"] ?? ""); }
            set { ViewState["Pmf_TextBox_IsCanEmpty"] = value; }
        }
        /// <summary>
        /// 验证表达式
        /// </summary>
        public string ValidationExpression
        {
            get
            {
                return (string) ViewState["TextBox_ValidationExpression"];
            }
            set
            {
                ViewState["TextBox_ValidationExpression"] = value;
            }
        }

        /// <summary>
        /// 给控件添加属性
        /// </summary>
        /// <param name="key">属性名</param>
        /// <param name="strValue">属性值</param>
        protected void AddAttribute(string key,string strValue)
        {
            this.Attributes.Add(key,strValue);
        }


        protected override void CreateChildControls()
        {
            this.Controls.Clear();
            if (!System.String.IsNullOrEmpty(this.MaxValue) || !System.String.IsNullOrEmpty(this.MinValue))
            {
                range.ControlToValidate = this.ID;
                range.Type = ValidationDataType.Double;

                if(null != this.MinValue && null != this.MaxValue)
                {
                    range.MaximumValue = this.MaxValue;
                    range.MinimumValue = this.MinValue;
                }
                else
                {
                    if(null != this.MaxValue)
                    {
                        range.MaximumValue = _maxValue;
                        range.MinimumValue = Int32.MinValue.ToString();
                    }
                    else if(null != _minValue)
                    {
                        range.MaximumValue = Int32.MaxValue.ToString();
                        range.MinimumValue = _minValue;
                    }
                }
                range.ErrorMessage = System.String.Format("请确保输入数据在{0}~{1}之间.", range.MinimumValue, range.MaximumValue);
                range.Display = ValidatorDisplay.Static;
                this.Controls.AddAt(0,range);
            }
            //base.CreateChildControls();

            if (!System.String.IsNullOrEmpty(RequiredFieldType) && (RequiredFieldType != "不验证"))
            {
                reg.Display = ValidatorDisplay.Dynamic;
                reg.ControlToValidate = this.ID;
                switch (RequiredFieldType)
                {
                    case "数字验证":
                        reg.ValidationExpression = this.ValidationExpression ?? @"^[-]?\\d+[.]?\\d*$";
                        reg.ErrorMessage = "数字格式不正确";
                        break;
                    case "电子邮箱":
                        reg.ValidationExpression = this.ValidationExpression ?? @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
                        reg.ErrorMessage = "电子邮箱格式不正确";
                        break;
                    case "移动电话":
                        reg.ValidationExpression = this.ValidationExpression ?? "^\\d{11}$";
                        reg.ErrorMessage = "移动电话的位数应为11位!";
                        break;
                    case "住宅电话":
                        reg.ValidationExpression = this.ValidationExpression ?? "((\\(\\d{3}\\) ?)|(\\d{3}-))?\\d{3}-\\d{4}|((\\(\\d{3}\\) ?)|(\\d{4}-))?\\d{4}-\\d{4}";
                        reg.ErrorMessage = "请依 (XXX)XXX-XXXX 格式或 (XXX)XXXX-XXXX 输入电话号码！";
                        break;
                    case "身份证号码":
                        reg.ValidationExpression = this.ValidationExpression ?? "^\\d{15}$|^\\d{18}$";
                        reg.ErrorMessage = "请依15或18位数据的身份证号！";
                        break;
                    case "网址验证":
                        reg.ValidationExpression = this.ValidationExpression ?? @"^(http|https)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{1,10}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$";
                        reg.ErrorMessage = "网址验证格式不正确";
                        break;
                    case "年月日":
                        reg.ValidationExpression = this.ValidationExpression ?? @"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-9]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$";
                        reg.ErrorMessage = "请输入正确的日期,如:2008-10-23";
                        break;
                    case "日期时间":
                        reg.ValidationExpression = this.ValidationExpression ?? @"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-9]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) (20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d$";
                        reg.ErrorMessage = "请输入正确的日期,如: 2008-10-23 21:10:25";
                        break;
                    case "货币金额":
                        reg.ValidationExpression = this.ValidationExpression ?? "^-?([0-9]|[0-9].[0-9]{0-2}|[1-9][0-9]*.[0-9]{0,2})$";
                        reg.ErrorMessage = "货币金额格式不正确";
                        break;
                    case "IP地址":
                        reg.ValidationExpression = this.ValidationExpression ?? @"(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$";
                        reg.ErrorMessage = "IP地址格式不正确";
                        break;
                    case "字母数字下划线":
                        reg.ValidationExpression = this.ValidationExpression ?? "^[0-9a-zA-Z_]+$";
                        reg.ErrorMessage = "字母数字下划线格式不正确";
                        break;
                    default:
                        break;
                }
                this.Controls.AddAt(0,reg);
            }
            switch (IsCanEmpty)
            {
                case "可为空":
                    break;
                case "必填":
                    isCanNull.Display = ValidatorDisplay.Dynamic;
                    isCanNull.ControlToValidate = this.ID;
                    isCanNull.ErrorMessage = @"<font style='color:red;'>请输入内容</span>";
                    this.Controls.AddAt(0,isCanNull);
                    break;
                default:
                    break;
            }
            this.ChildControlsCreated = true;
        }

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            if (!string.IsNullOrEmpty(_hintTitle)) this.AddAttribute("hintInfo", this._hintTitle);
            
            base.Render(writer);
            RenderChildren(writer);
        }

    }

    internal class IsCanEmptyControlConverter :StringConverter
    {
        /// <summary>
        /// 下拉列表编辑属性
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
        {
            return true;
            //return base.GetStandardValuesSupported(context);
        }
        public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
        {
            return false;
            //return base.GetStandardValuesExclusive(context);
        }
        public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            List<string> lists = new List<string>(5);
            lists.Add("可为空");
            lists.Add("必填");
            return new StandardValuesCollection(lists);
            
        }
    }
}
